/* eslint-disable @typescript-eslint/no-unused-vars */
import { Device, GatewayType } from "@/api/interface/iot";
import { modifyGateway, getGatewayList, removeGateway, saveToProduct, syncGateway, changeGroup } from "@/api/modules/iot/gateway";
import { serviceStart, serviceStop } from "@/api/modules/service/service";
import DialogBox from "@/components/DialogBox";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import DeptTree from "@/components/Sansan/DeptTree";
import OnlineStatus from "@/components/Sansan/OnlineStatus/OnlineStatus";
import SelectDeptList from "@/components/Sansan/SelectDeptList";
import { MessageType } from "@/enums/messageEnum";
import { RouterPath } from "@/enums/routerPath";
import { DeviceStatusEnum } from "@/enums/statusEnum";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { AuthBtns } from "@/utils/constants";
import { dataFormat } from "@/utils/format";
import { gotoPage } from "@/utils/routerUtil";
import { confirm, showMsg, showTips } from "@/utils/util";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import SaveToProduct from "../product/components/SaveToProduct";
import BasicDialog from "./components/basicInfo/basicDialog";
import { useAddress } from "@/hooks/useAddress";
import BaseMap from "@/components/Map/antvl7/BaseMap";
export default defineComponent({
	name: "SoftGatewayList",
	setup() {
		const router = useRouter();
		const initParam = reactive<Device.ReqGateway>({});

		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total,
				pageIndex: data.current,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			// return { result: { records: [{}, {}] } };
			return getGatewayList(params, GatewayType.SoftGateway);
		};
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons();
		});
		onActivated(() => {
			proTable.value.getTableList();
		});
		// buttonsList.value = [
		// 	{
		// 		text: "添加",
		// 		component: "add",
		// 		type: "primary"
		// 	}
		// ];
		const addDialog = reactive<any>({
			title: "添加网关",
			visible: false
		});
		const clickBtn = async (fn: string, scope: any) => {
			let selectList = scope.row ? [scope.row] : scope.selectList;
			switch (fn) {
				case "assignGroup":
					if (!selectList.length) {
						showMsg("请选择要操作的设备", MessageType.warning);
						return;
					}
					assignGroupDialog.detail.selectList = selectList;
					assignGroupDialog.visible = true;
					break;
				case "updateLocation":
					if (selectList.length != 1) {
						showMsg("请选择一个设备", MessageType.warning);
						return;
					}
					updateLocationDialog.detail = { ...(selectList[0] || {}) };
					updateLocationDialog.visible = true;
					break;
				case "mod":
					if (selectList.length != 1) {
						showMsg("请选择一个设备", MessageType.warning);
						return;
					}
				case "details":
					router.push({
						path: RouterPath.gatewayDetail,
						query: { sn: selectList[0].sn, type: selectList[0].type, menuId: AuthBtns.softGateway }
					});
					break;
				case "sync":
					syncGateway({ idSn: selectList.map((item: any) => item.sn).join(",") }).then(res => {
						showTips(res.code, "下发同步网关配置命令");
					});
					break;
				case "add":
					initGatewayDetail();
					addDialog.visible = true;
					break;
				case "del":
					if (scope.selectedListIds.length == 1) {
						confirm({ content: "删除后无法找回，确定删除当前选择的网关" }).then(flag => {
							flag && submitDel({ idSn: scope.selectedListIds.toString() });
						});
					} else {
						showMsg("请选择一条数据删除", MessageType.warning);
					}
					break;
				case "stop":
					if (!selectList[0]) {
						showMsg("请选择要操作的网关", MessageType.warning);
						return;
					}
					serviceStop({ instanceId: selectList[0].sn }).then(res => {
						showTips(res.code, "停止网关") && proTable.value.getTableList();
					});
					break;
				case "start":
					if (!selectList[0]) {
						showMsg("请选择要操作的网关", false);
						return;
					}
					serviceStart({ instanceId: selectList[0].sn }).then(res => {
						showTips(res.code, "网关重启") && proTable.value.getTableList();
					});
					break;
				case "saveToProduct":
					if (selectList.length != 1) {
						showMsg("请选择一个设备另存为产品", MessageType.warning);
						return;
					}
					saveToProductDialog.formData.id = selectList[0].sn;
					saveToProductDialog.formData.name = selectList[0].name;
					saveToProductDialog.visible = true;
					break;
			}
		};

		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "onlineStatus", label: "状态", width: 80, search: { slot: {} } },
			{ prop: "sn", label: "网关编号", width: 180, search: { el: "input" } },
			{ prop: "name", label: "网关名称", width: 180, search: { el: "input" } },
			{ prop: "deptName", label: "所属分组", width: "120", search: { slot: {} } },
			{ prop: "lastLiveTime", label: "末次交互", width: 170 },
			{ prop: "logoutTime", label: "掉线时间", width: 170 },
			{ prop: "location", label: "位置" },
			{ prop: "operation", label: "操作", fixed: "right", width: 130 }
		];
		const assignGroupDialog = reactive<any>({
			visible: false,
			title: "调整分组",
			detail: {
				selectList: [],
				deptId: "",
				deptName: ""
			}
		});
		//调整分组
		const submitAssignGroup = async () => {
			let { code } = await changeGroup(
				{
					idSn: assignGroupDialog.detail.selectList.map((item: any) => item.id).toString(),
					deptId: assignGroupDialog.detail.deptId
				},
				GatewayType.SoftGateway
			);
			let ok = showTips(code, "调整分组");
			if (ok) {
				assignGroupDialog.visible = false;
				proTable.value.getTableList();
			}
		};
		const proTable = ref<any>();
		const detail = reactive<any>({ location: {}, type: GatewayType.SoftGateway });
		const submitDel = async (dataInfo: any) => {
			let res = await removeGateway({ ...dataInfo }, GatewayType.SoftGateway);
			let ok = showTips(res.code, "删除");
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.reset();
			}
		};
		const submitAdd = (ok: boolean) => {
			if (ok) {
				initGatewayDetail();
				addDialog.visible = false;
				proTable.value.reset();
			}
		};
		const saveToProductDialog = reactive<any>({
			visible: false,
			formData: {
				id: "",
				name: "",
				type: GatewayType.Device
			}
		});

		const submitToProduct = async (data: Device.ReqProduct) => {
			let { code } = await saveToProduct(data);
			let ok = showTips(code, "设备另存为产品");
			if (ok) saveToProductDialog.visible = false;
		};

		//由use hooks中进行回调（不同类型网关的GatewayType不一样）
		const updateGatewayInfo = async (data: any) => {
			return modifyGateway(data, GatewayType.SoftGateway);
		};
		const initGatewayDetail = () => {
			detail.sn = "";
			detail.name = "";
			detail.deptId = "";
			detail.progrom = "";
			detail.productModel = "";
		};
		const { updateLocationDialog, submitLocation } = useAddress(updateGatewayInfo, proTable);
		return () => {
			return (
				<div>
					<SaveToProduct
						title="另存为产品"
						v-model:visible={saveToProductDialog.visible}
						formData={saveToProductDialog.formData}
						width="600px"
						onSubmit={(data: Device.ReqProduct) => {
							submitToProduct(data);
						}}
					></SaveToProduct>
					<DialogBox
						class="dialog-dense"
						title={assignGroupDialog.title}
						v-model:visible={assignGroupDialog.visible}
						width="500px"
					>
						<DeptTree detail={assignGroupDialog.detail} onChange={() => submitAssignGroup()} class="p-8" />
					</DialogBox>
					<BasicDialog
						width="700px"
						title={addDialog.title}
						v-model:visible={addDialog.visible}
						detail={detail}
						onSubmit={(ok: boolean) => submitAdd(ok)}
					></BasicDialog>
					<DialogBox
						class="dialog-dense"
						title={updateLocationDialog.title}
						v-model:visible={updateLocationDialog.visible}
						onConfirm={() => submitLocation()}
					>
						{updateLocationDialog.visible ? (
							<BaseMap style="height:50vh" editerMarker detail={updateLocationDialog.detail} />
						) : null}
						<div class="address-detail">{updateLocationDialog.detail.location?.address}</div>
					</DialogBox>
					<ProTable
						ref={proTable}
						title={buttonsList.value.length ? "" : "网关管理"}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						searchCol={5}
						dataCallback={dataCallback}
					>
						{{
							"search-onlineStatus": () => {
								return (
									<el-select v-model={initParam.onlineStatus} style="width:100px">
										<el-option label="全部" value=""></el-option>
										<el-option label="在线" value={DeviceStatusEnum.ONLINE}></el-option>
										<el-option label="离线" value={DeviceStatusEnum.OFFLINE}></el-option>
									</el-select>
								);
							},
							"search-deptName": () => {
								return <SelectDeptList detail={initParam} appendChild onChange={val => (initParam.deptId = val.id)} />;
							},
							tableHeader: (scope: any) => {
								return buttonsList.value?.map((item: any) => {
									return (
										<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
											<i class={`iconfont ${item.icon}`}></i>
											{item.menuName}
										</el-button>
									);
								});
							},
							sn: (scope: any) => {
								return (
									<div class="truncate cursor-pointer primary-color" title="查看详情" onClick={() => clickBtn("details", scope)}>
										{scope.row.sn}
									</div>
								);
							},
							productModel: (scope: any) => {
								return scope.row.productModel ? (
									<div
										title="查看产品"
										class="truncate cursor-pointer primary-color"
										onClick={() => gotoPage(RouterPath.productDetail, { productModel: scope.row.productModel })}
									>
										{scope.row.productModel}
									</div>
								) : (
									"--"
								);
							},
							location: (scope: any) => {
								return (
									<div
										title="设置位置"
										class="truncate cursor-pointer primary-color"
										onClick={() => clickBtn("updateLocation", scope)}
									>
										{scope.row.location?.address || "--"}
									</div>
								);
							},
							lastLiveTime: (scope: any) => {
								return dataFormat("datetime", scope.row.lastLiveTime);
							},
							logoutTime: (scope: any) => {
								return dataFormat("datetime", scope.row.logoutTime);
							},
							onlineStatus: (scope: any) => {
								return <OnlineStatus v-model={scope.row.onlineStatus} />;
							},
							operation: (scope: any) => {
								return (
									<>
										<el-link
											type="primary"
											link
											class="iconfont iconbx-file"
											onClick={() => {
												clickBtn("details", scope);
											}}
										>
											详情
										</el-link>
									</>
								);
							},
							empty: () => {
								return (
									<div>
										<Empty
											class="text-left leading-6"
											subtitle="与平台建立连接，并代理子设备连接到平台，实现子设备与平台的数据互联互通。"
											btnText="添加网关"
											onClick={(scope: any) => {
												clickBtn("add", scope);
											}}
										/>
									</div>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
